<?php
namespace app\controller\web;

use app\service\AdminPathinfoService;
use app\exception\ErrnoPlus;
use app\service\AdminAcountService;
use share\controller\ApiBaseController;
use share\controller\ControllerValidateTrait;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\ContextService;
use think\Controller;
use think\response\Json;

class WebBaseController extends ApiBaseController{

    protected $beforeActionList = [
        "checkUser",
    ];

    protected $_userInfo = null;

    
    /**
     * @param array $data
     * @return \think\response\Json
     */
    public static function json_out($data,$isLog = true){         
        return new Json($data);
    }

    /**
     * @return \think\response\Json
     */
    public static function ok($data = [],$msg = 'success',$code = 0){
        $resp = [
            'resultCode' => $code ,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    }

    /**
     * @return \think\response\Json
     */
    public static function fail( $msg, $code = Errno::COMMON_UNKNOWN, $data = []){
        $resp = [
            'resultCode' => $code,
            'errorString' => $msg,
        ];
        if($data){
            $resp['body'] = $data;
        }
        return self::json_out($resp);
    }

    /**
     * 格式化输出页面数据
     * @param array $page
     * @param int $total
     * @param array|null $data
     * @return array
     */
    public static function formatPageData($page,$total,$data = null){
        return [
            'page' => $page['page'],
            'size' =>  $page['size'],
            'total' =>  $total,
            'data' => $data,
        ];
    }

    /**
     * 检查已登录用户
     */
    public function checkUser(){        
        $path = $this->request->pathinfo();
        $method = strtolower($this->request->method());
        $token = $this->request->header('token');      
        if(empty($token)){
            throw new ApiException("当前用户未登录",ErrnoPlus::WEB_LOGOUT);
        }
        if($path[0] !== '/'){
            $path = '/'.$path;
        }

        $userInfo = AdminAcountService::getLoginAdminInfo($token);
        if(!empty($userInfo)){
            ContextService::setUserInfo($userInfo); 
            AdminAcountService::keepLoginByToken($token);
            // 超管不需要权限检查
            if(intval($userInfo['level']) === 0){
                return;
            }
        }
        // 检查是否需要登录
        if(AdminPathinfoService::isNeedLogin($path,$method )){           
            if(empty($userInfo)){
                throw new ApiException("登录超时",ErrnoPlus::WEB_LOGOUT);
            } 

            if(!AdminPathinfoService::hasApiPremission($userInfo,$path,$method)){
                throw new ApiException("暂无权限",ErrnoPlus::COMMON_ERROR);
            }
            return;
        }
    }
}